import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { BaseComponent } from 'src/api/base_component';
import { TagType } from 'src/api/dto';

export class AddTagArg {
  id: number = -1;
  name: string = '';
  note: string = '';
  beginTime: number = -1;
  endTime: number = -1;
  tagTypeMap: Map<string, TagType> = new Map();
}

@Component({
  selector: 'add-tag-dialog',
  templateUrl: 'add-tag-dialog.html',
})
export class AddTagDialog extends BaseComponent {
  constructor(public dialogRef: MatDialogRef<AddTagDialog>, @Inject(MAT_DIALOG_DATA) public data: AddTagArg) {
    super();
    this.beginTimeStr = new Date(data.beginTime).toLocaleString();
    this.endTimeStr = new Date(data.endTime).toLocaleString();
    if (data.id != -1) {
      this.tagColor = data.tagTypeMap.get(data.name)!.color;
      this.name = data.name;
    }
  }

  beginTimeStr = '';
  endTimeStr = '';

  tagColor = '';
  name = '';

  computeDuration(): string {
    const duration = new Date(new Date(this.endTimeStr).getTime() - new Date(this.beginTimeStr).getTime());
    return `${duration.getUTCHours()}:${duration.getUTCMinutes()}:${duration.getUTCSeconds()}`;
  }

  changeColor() {
    this.api()
      .update_tag_type(this.data.tagTypeMap.get(this.data.name)!.id, null, this.tagColor)
      .then((success) => {
        if (success) {
          alert('ok!');
        }
      });
  }

  onNo(): void {
    this.dialogRef.close();
  }

  onOK(): void {
    this.data.beginTime = new Date(this.beginTimeStr).getTime();
    this.data.endTime = new Date(this.endTimeStr).getTime();
    this.dialogRef.close(this.data);
  }
}
